/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aletex.ui.security;

import aletex.da.UserFacade;
import aletex.entity.User;
import aletex.ui.util.JsfUtil;
import aletex.util.PasswordGenerator;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author cibervn
 */
@ManagedBean
@SessionScoped
public class LoginController implements Serializable {

    @EJB
    private UserFacade userJpa;
    private String requestURL;
    private String pathInfo;
    private User user;
    private String username;
    private volatile String password;

    /**
     * Creates a new instance of LoginController
     */
    public LoginController() {
    }

    public String login() {
        user = authenticate(username, password);
        if (user != null) {
            if (pathInfo == null || pathInfo.trim().equals("") || pathInfo.equals("/login.xhtml")) {
                pathInfo = "/home.xhtml";
            }
            return pathInfo + "?faces-redirect=true";
        }
        JsfUtil.addErrorMessageKey("Login_Fails");
        return "";
    }

    public String logout() {
        user = null;
        return "";
    }

    public String getAutoRedirect() throws IOException {
        if (user == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            pathInfo = context.getExternalContext().getRequestPathInfo();
            String contextPath = context.getExternalContext().getRequestContextPath();
            ((HttpServletResponse) context.getExternalContext().getResponse()).sendRedirect(contextPath + "/faces/login.xhtml");

        }
        return "";
    }

    /**
     *
     * @param username
     * @param password
     * @return user that is authentificated, null otherwise
     */
    private User authenticate(String username, String password) {
        //Validate input data
        if (username == null || password == null) {
            return null;
        }
        try {
            //We work only with username is lowercase
            username = username.toLowerCase();
            //Encrypt password
            String hashPw = PasswordGenerator.hashPassword(password);
            //Looking for user with that username
            User u = userJpa.findUserByUsername(username);
            //If username does not exist or with different password, login fails
            if (u != null && u.getPassword().equals(hashPw)) {
                return u;
            }
        } catch (Exception ex) {
            Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public User getUser() {
        return user;
    }
}
